﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using ESF.General.Text;
using ESF.Data;
using System.Data;
using ESF.General;
using System.Text;

#endregion


namespace ESF.SFT.DataAccess
{
	public static class AdoMetadataPublisher
	{
		#region Arrojar Datos a PISIS Neo

		public static FileRegisterValidatorSet GetValidatorSet(string pShortIdentificator)
		{
			IDbCommand cmd;

			DbReader PISIS_Read = new DbReader("PISIS");


			cmd = PISIS_Read.CreateSPCommand("P_GetUserSchemaInfo");

			PISIS_Read.AddParameter(cmd, "pShortIdentificator", pShortIdentificator);

			return PISIS_Read.Get<FileRegisterValidatorSet>(cmd, ConvertTo);
		}

		 
		public static List<FileRegisterValidatorSet> GetAll(string pUserName)
		{
			IDbCommand cmd;

			DataRow drUsuario;

			DbReader PISIS_Read = new DbReader("PISIS");
			
			DbReader SEGURIDAD_Read = new DbReader("SEGURIDAD");


			if (!string.IsNullOrEmpty (pUserName))
			{
				// TODO: Sacarlo como llamado a servicio
				cmd = SEGURIDAD_Read.CreateSPCommand ("PRBObtenerDetalleUsuario");

				SEGURIDAD_Read.AddParameter (cmd, "pLogin", pUserName);

				drUsuario = SEGURIDAD_Read.GetFirstRow (cmd);

				if (drUsuario == null)
				{
					throw new GenericException (string.Format ("No hay datos para el usuario: {0}", pUserName));
				}


				cmd = PISIS_Read.CreateSPCommand("P_GetUserSchemaInfo");

				PISIS_Read.AddParameter(cmd, "pEnterpriseIdentificationType", drUsuario["EntidadTipoID"]);
				PISIS_Read.AddParameter(cmd, "pEnterpriseIdentificationNumber", drUsuario["EntidadNroID"]);
			}
			else
			{
				cmd = PISIS_Read.CreateSPCommand("P_GetUserSchemaInfo");
			}

			return PISIS_Read.GetList<FileRegisterValidatorSet>(cmd, ConvertTo);
		}


		private static FileRegisterValidatorSet ConvertTo(IDataReader pReader, string pPrefix = "", string pListLoading = "")
		{
			FileRegisterValidatorSet result;


			result = new FileRegisterValidatorSet()
			{
				ID = DataHelper.GetInt (pReader, "CodEsquema"),
				Name = DataHelper.GetString (pReader, "Nombre"),
				Separator = DataHelper.GetString (pReader, "SeparadorCampos", ",")[0],
				Version = DataHelper.GetString (pReader, "Version"),
				BaseFileName = DataHelper.GetString (pReader, "BaseNombreArchivo"),
				RequiresDigitalCertificate = DataHelper.GetBool(pReader, "RequiresDigitalCertificate", true),
				AcceptedExtensions = TextHelper.Split('|', DataHelper.GetString(pReader, "ExtensionesAceptables")).ToArray (),
				ValidateTextData = DataHelper.GetBool(pReader, "EsArchivoPlano", true),
				Features = TextHelper.Split('|', DataHelper.GetString(pReader, "Features")).ToArray(),
				FileMaxLengthBytes = DataHelper.GetInt(pReader, "MaximoTamanioArchivoBytes", 104857600),
				OptionalDigitalCertificate = DataHelper.GetBool(pReader, "OptionalDigitalCertificate", false),
				DatePortionNames = TextHelper.Split('|', DataHelper.GetString(pReader, "DatePortionNames")).ToArray(),
				RequiresEnterpriseIdentificationInFile = DataHelper.GetBool(pReader, "RequiresEnterpriseIdentificationInFile", true),
				RequiresCMS = DataHelper.GetBool(pReader, "RequiresCMS")
			};

			if (DataHelper.IsEmpty(result.AcceptedExtensions)) { return null; }

			// Ajustar extensiones por formato .ext
			for (int i = 0; i < result.AcceptedExtensions.Count(); i++)
			{
				if (!result.AcceptedExtensions[i].StartsWith("."))
				{
					result.AcceptedExtensions[i] = "." + result.AcceptedExtensions[i];
				}
			}

			result.AcceptedExtensions = result.AcceptedExtensions.Distinct().ToArray();

			switch (pReader["CodTipoTexto"].ToString())
			{
				case "ASCII": result.CodePage = Encoding.ASCII.CodePage; break;
				case "UTF16": result.CodePage = Encoding.Unicode.CodePage; break;
				default: result.CodePage = Encoding.Default.CodePage; break;
			}

			result.Validators = AdoFileRegisterValidator.GetValidators (result);

			result.FileNameRegularExpression =
				String.Join(string.Empty,
					from V in result.Validators
					orderby V.Position
					where V.RegisterType == 0
					select V.RegularExpression + (V.IsRequired ? string.Empty : "?"));

			result.OnlyDatePortions = (from V in result.Validators
									   orderby V.Position
									   where
										   V.RegisterType == 0
										   && result.DatePortionNames.Contains(V.Name)
									   select
										   new KeyValuePair<string, int>(
											   V.Name,
											   (from VX in result.Validators
												where
													VX.RegisterType == 0
													&& VX.Position < V.Position
												select VX.Length).Sum().Value
										   )
				).ToList();

			result.OnlyNameAllowedValues = (from V in result.Validators
											orderby V.Position
											where 
												V.RegisterType == 0
											select new KeyValuePair<int, string[]>(V.Length.Value, V.AllowedValues)).ToList();

			return result;
		}
		
		#endregion
	}
}